package com.erpanderp.wam.util;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.validation.ValidationException;

import com.itextpdf.text.log.SysoLogger;

public class ValidationUtil {


	private static final String TIME24HOURS_PATTERN = "([01]?[0-9]|2[0-3]):[0-5][0-9]";

	public static String validate24HoursTime(String inputTime, String fieldName, String componentId, FacesContext facesContext) {
		String warningMessage = null;
		
		Pattern pattern = Pattern.compile(TIME24HOURS_PATTERN, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputTime);
		if (matcher.matches()) {
			warningMessage = null;
		} else {
			warningMessage = fieldName + " is invalid.";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;
	}

	public static String getTimeDifference(String inTime, String outTime, String componentId){
		SimpleDateFormat format = new SimpleDateFormat("HH:mm");
	    Date date1 = null;
	    Date date2 = null;
		
	    try {
			date1 = format.parse(inTime);
			date2 = format.parse(outTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    String timeDifferenceString = null;
	    System.out.println(date2.getTime() + " " + date1.getTime());
		long difference = date2.getTime() - date1.getTime();
        System.out.println(difference);
		if(difference < 0){
			FacesMessage fm = new FacesMessage("Out Time should be greater than In Time.");
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
			return "INVALID TIMES";
		}else{
			difference = difference / 60000;
	        if (difference > 60) {
	            int Hour = (int) (difference / 60);
	            int Mins = (int) (difference % 60);
	            if (Mins == 0)
	            	timeDifferenceString = String.valueOf(Hour).length() == 1 ? ("0" + Hour) : Hour + ":00";
	            else
	            	timeDifferenceString = (String.valueOf(Hour).length() == 1 ? ("0" + Hour) : Hour) + ":" + (String.valueOf(Mins).length() == 1 ? ("0" + Mins) : Mins);
	        } else {
	        	timeDifferenceString = "00:" + (String.valueOf(difference).length() == 1 ? ("0" + difference) : difference);
	        }
	        if(!timeDifferenceString.contains(":")){
	        	timeDifferenceString += ":00";
	        }
	        return timeDifferenceString;
		}
		
	}
	
	public static void gotoLoginPage() {
		try {
			FacesContext.getCurrentInstance().getExternalContext()
					.redirect("/wam/login.html");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String redirect() {
		System.out.println("RETURN LOGIN OUT COME");
		return "login";
	}

	public static String isEmpty(String inputValue, String fieldName,
			String componentId, FacesContext facesContext) {
		String warningMessage = null;

		if (inputValue != null && !inputValue.equals("")) {
			warningMessage = null;
		} else {
			warningMessage = fieldName + " cannot be empty.";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;
	}

	public static String isNonZero(Object inputValue, String fieldName,
			String componentId, FacesContext facesContext) {
		String warningMessage = null;

		if (inputValue != null && Long.parseLong(inputValue.toString()) != 0) {
			warningMessage = null;
		} else {
			warningMessage = fieldName + " cannot be empty.";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;
	}

	public static String isReentered(String inputValue, String fieldName,
			String componentId, FacesContext facesContext) {
		String warningMessage = null;

		if (inputValue != null && !inputValue.equals("")) {
			warningMessage = null;
		} else {
			warningMessage = "Please reenter " + fieldName;
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;
	}

	public static String isEmailValid(String inputValue, String fieldName,
			String componentId, FacesContext facesContext) {

		System.out.println("IS EMAIL VALID CALLED");
		System.out.println("PASSED EMAIL:" + inputValue);
		String warningMessage = null;
		emailValidation(inputValue);
		if (emailValidation(inputValue)) {
			System.out.println("EMAIL VALIDATION IS TRUE isValid: TRUE");
			warningMessage = null;
		} else {
			warningMessage = fieldName + " Should be in valid format";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;

		// if(inputValue != null && !inputValue.equals("")){
	}

	public static String isPANNUMBERValid(String inputValue, String fieldName,
			String componentId, FacesContext facesContext) {

		System.out.println("IS PAN NUMBER VALID CALLED");
		System.out.println("PAN NUMBER:" + inputValue);
		String warningMessage = null;

		if (isPANValid(inputValue)) {
			System.out.println("PAN NUMBER VALIDATION IS TRUE isValid: TRUE");
			warningMessage = null;
		} else {
			warningMessage = fieldName + " Should be in valid format";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;

		// if(inputValue != null && !inputValue.equals("")){
	}

	
	
	
	public static String isMARKSPERCENTAGEVALID(String inputValue, String fieldName,
			String componentId, FacesContext facesContext) {

		System.out.println("IS MARKS VALID CALLED");
		System.out.println("PAN NUMBER:" + inputValue);
		String warningMessage = null;

		if (isMARKSValid(inputValue)) {
			System.out.println("MARKS VALIDATION IS TRUE isValid: TRUE");
			warningMessage = null;
		} else {
			warningMessage = fieldName + " Should be in valid format";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;

		// if(inputValue != null && !inputValue.equals("")){
	}
	public static String isPASSPORTNUMBERValid(String inputValue,
			String fieldName, String componentId, FacesContext facesContext) {

		System.out.println("IS PASSPORT VALID CALLED");
		System.out.println("PASSED PASSPORT NUMBER:" + inputValue);
		String warningMessage = null;

		if (isPASSPORTValid(inputValue)) {
			System.out.println("PASSPORT VALIDATION IS TRUE isValid: TRUE");
			warningMessage = null;
		} else {
			warningMessage = fieldName + " Should be in valid format";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;

		// if(inputValue != null && !inputValue.equals("")){
	}

	public static String isDRIVINGLICENSENUMBERValid(String inputValue,
			String fieldName, String componentId, FacesContext facesContext) {

		System.out.println("IS DIVING LICENSE VALID CALLED");
		System.out.println("DRIVING LICENSE VALUE:" + inputValue);
		String warningMessage = null;

		if (isDRIVINGLICENSEValid(inputValue)) {
			System.out
					.println("DRIVING LICENSE VALIDATION IS TRUE isValid: TRUE");
			warningMessage = null;
		} else {
			warningMessage = fieldName + " Should be in valid format";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;

		// if(inputValue != null && !inputValue.equals("")){
	}
	
	public static String isDOBDateValid(String inputValue,
			String fieldName, String componentId, FacesContext facesContext) {

		System.out.println("IS DOB DATE VALID CALLED");
		System.out.println("DOB VALUE:" + inputValue);
		String warningMessage = null;

		if (isBirthDateValid(inputValue)) {
			System.out
					.println("DOB VALIDATION IS TRUE isValid: TRUE");
			warningMessage = null;
		} else {
			warningMessage = fieldName + "Please enter correct date of birth";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;

		// if(inputValue != null && !inputValue.equals("")){
	}
	

	public static boolean emailValidation(String email) {
		 boolean isValid = false;
		System.out.println("EMAIL VALIDATION IN PROGRESS");
		System.out.println("Passed email:" + email);
		String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence inputStr = email.trim();
		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValid = true;
		} else {
			isValid = false;
			System.out.println("VALID EMAIL VALID RETURNED:" + isValid);
			return isValid;
		}
		System.out.println("VALID EMAIL VALID RETURNED:" + isValid);

		return isValid;

	}

	public static boolean isPANValid(String pan) {
		boolean isValid = false;
		String expression = "^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$";
		CharSequence inputStr = pan.trim();
		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			char c = pan.charAt(3);
			if(c == 'P'){
				isValid = true;	
			}
			
		}
		return isValid;
	}
	
	public static boolean isMARKSValid(String marks) {
		boolean isValid = false;
		String expression = "^(?:[1-9]\\d*|0)?(?:\\.\\d+)?$";
		CharSequence inputStr = marks.trim();
		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			
				isValid = true;	
			
			
		}
		return isValid;
	}

	public static boolean isDRIVINGLICENSEValid(String drivingLicense) {
		boolean isValid = false;
		String expression = "^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$";
		CharSequence inputStr = drivingLicense.trim();
		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValid = true;
		}
		return isValid;
	}

	public static boolean isPASSPORTValid(String passport) {
		boolean isValid = false;
		String expression = "^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$";
		CharSequence inputStr = passport.trim();
		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValid = true;
		}
		return isValid;
	}
	public static boolean isBirthDateValid(String dateOfBirth) {
        boolean isValid = false;
		System.out.println(dateOfBirth.trim().substring(dateOfBirth.length() - 4));
		int birthYear = Integer.parseInt(dateOfBirth.trim().substring(dateOfBirth.trim().length() - 4));
		int currentYear;
		int yearDiff;
		
		currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
		yearDiff = currentYear - birthYear;
	  
		if(yearDiff >= 20 && yearDiff <= 100){
			isValid = true;
		}
		
		System.out.println("DOB valid: " + isValid);
		return isValid;		
	}
	
	public static String isSalaryValid(String number,String fieldName,String componentId,FacesContext facesContext) {
	
		String warningMessage = null;

		String expression = "[0-9]{5,7}";
		CharSequence inputStr = number;
		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		System.out.println("========VALIDATION UTIL -------"+matcher.matches());
		System.out.println("=========VALIDATION UTIL ---number----"+number);
		if (matcher.matches()) {
			 if(number.length() < 4) {
					warningMessage = fieldName + " should contain more than 5 numbers.";
					FacesMessage fm = new FacesMessage(warningMessage);
					fm.setSeverity(FacesMessage.SEVERITY_WARN);
					FacesContext.getCurrentInstance().addMessage(componentId, fm);
			 }else{
					warningMessage = null; 
			 }
		
		
		}else {
			System.out.println("=========VALIDATION UTIL ---number-ELSE--"+number);
			System.out.println("VALIDATION UTIL -else------"+matcher.matches());
			warningMessage = fieldName + " must be a valid 5 digit positive integer/number.";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;
		
	}
	
	public static String isValidPositiveFloatNumber(String number,String fieldName,String componentId,FacesContext facesContext) {
		
		String warningMessage = null;

		//String expression = "[0-9.][0-9]$";
		//String expression ="[0-9]*\\.?[0-9]+$ "; //
		String expression = "^(?:[1-9]\\d*|0)?(?:\\.\\d+)?$";
		CharSequence inputStr = number;
		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			warningMessage = null;
		}else{
			warningMessage = fieldName + " must be a valid positive value.";
			FacesMessage fm = new FacesMessage(warningMessage);
			fm.setSeverity(FacesMessage.SEVERITY_WARN);
			FacesContext.getCurrentInstance().addMessage(componentId, fm);
		}
		return warningMessage;
		
	}
	
	public static void main(String a[]){
		//System.out.println(ValidationUtil.validate24HoursTime("22:00", "", "", null));
		System.out.println(ValidationUtil.isValidPositiveFloatNumber("a.1", "field",null, null));
	} 

}
